<?php

namespace App\Http\Controllers\Api;

use App\Http\Helper\BusinessHelper;
use App\Services\OpensslEncryptHelper;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use WechatUserService;
use App\Services\IdEncryptService;
use TestingDevUrlService;
use App\Models\LogHelper;
use TestingConfig;
use TestingChannelService;
use DB;
use UserChannelChangeService;
use TestingUserInfoService;
use TestingSyncOrderService;

class UserController extends Controller
{
    public function init(Request $request){
        $user_ip_int = rand(1000,9999);
        $encrypt_user = IdEncryptService::encryption($user_ip_int,'encode');
        $data = ['uid'=>$encrypt_user];
        return apiSuccess($data);
    }

    public function auth($developerCode, $callbackUrl){
        LogHelper::log("goto auth==============>");
        try{
            $callbackUrl = base64_decode($callbackUrl);
        }catch (Exception $e){
            return apiFailed(null,'url not correct');
        }

        LogHelper::log("callbackUrl=============>" . $callbackUrl);
//        $callbackUrl = 'http://tt.qiezilife.com/#!/home';
//        $callbackUrl = urlencode($callbackUrl);
//        dd('auth');
//        添加url的路径，将url作为值保存到developer_url表中
//        $callbackUrl = urldecode($callbackUrl);
        //适配第三方平台http://tt.qiezilife.com/quesdetail/try/Z0xM6D3yJb/0&appid=cwrefvervevretve
        $arr = explode('&', $callbackUrl);
        $callbackUrl = $arr[0];
        //appid=cwrefvervevretve
        $authorize_appid = isset($arr[1]) ? $arr[1] : "";
        if($authorize_appid){
            $authorizeArr = explode("=",$authorize_appid);
            $authorize_appid = "appid=".base64_decode($authorizeArr[1]);
        }
        LogHelper::log("authorize_appid=============>".$authorize_appid);
        if(in_weixin() || in_windows_weixin()){
            WechatUserService::qieziAccountCenterWechatAuth($developerCode, $callbackUrl, $authorize_appid);
        }else{
            WechatUserService::qieziAccountCenterMobileAuth($developerCode, $callbackUrl, $authorize_appid);
        }
    }

    /**
     * 通过茄子帐号中心回调的url
     * @param $thirdPartyCbUrlId
     * @param $uid
     * @param string $authorize
     */
    public function qieziAccountCallback($thirdPartyCbUrlId, $uid, $authorize=""){
        $devUrlInfo = TestingDevUrlService::getById($thirdPartyCbUrlId);
        $redirectUrl = $devUrlInfo['redirect_url'];
        //将茄子帐号中心的用户信息保存到本地的用户数据库
        WechatUserService::checkAccountCenterUserInfo($uid, $devUrlInfo, $authorize);
        $uid = IdEncryptService::encryption($uid, 'encode');
        $params = [];
        array_push($params, $uid);
        $url = [];
        array_push($url, $redirectUrl);
        array_push($url, implode('/', $params));
        $redirectUrl = implode('/', $url);
        //第三方平台返回url  http://tt.qiezilife.com/quesdetail/try/dJz2J624G6/grVKqrY2KR?cerverveverv
        if($authorize){
            $redirectUrl = $redirectUrl . "?appid=" . $authorize;
        }
        LogHelper::log('=======>redirectUrl_authorize' . $redirectUrl, 'Wx_ticket');
        //$this->log($redirectUrl);
        redirectToUrl($redirectUrl);
    }

    public function checkUserInfo($uid,Request $request){
        //处理第三方uid对应的逻辑。判断uid是否为第三方的uid还是为我们帐号中心的uid
        if($decodeData = IdEncryptService::encryption($uid,'decode')){
            $uid = $decodeData[0];
        }
        $status = 0;
        $user = WechatUserService::getByUid($uid);
        $componentAppids = TestingConfig::getValue('testing.component.appids');
        $componentAppids = json_decode($componentAppids,true);
        $inputAppid = $request->input('appid');
        $appid = base64_decode($inputAppid);
        if(!$user['wx_union_id'] && in_array($appid,$componentAppids) ){
            $status = 1;
        }
        $result['status'] = $status;
        return apiSuccess($result);
    }

    /**
     * 用户绑定渠道
     * @param Request $request
     * @return array
     */
    public function bindChannel(Request $request) {
        $uid = $request->input('uid');
        if($decodeData = IdEncryptService::encryption($uid, 'decode')){
            $uid = $decodeData[0];
        }
        $channelCode = $request->input('channel');
        if (!$channelCode) {
            return apiSuccess([5, $uid]);
        }
        if ($channel = TestingChannelService::getOneByCode($channelCode)) {
            $user = WechatUserService::getByUid($uid);
            if ($user && $user['channel_code'] != $channelCode) {
                $result = DB::transaction(function () use ($user, $channelCode) {
                    $result = UserChannelChangeService::store([
                        'uid' => $user['uid'],
                        'old_channel' => $user['channel_code'],
                        'new_channel' => $channelCode,
                        'add_time' => time()
                    ]);
                    $res = WechatUserService::updateByUid($user['uid'], [
                        'channel_code' => $channelCode,
                    ]);
                    return $res && $result;
                }, 5);
                if ($result) {
                    return apiSuccess([1, $uid]);
                }
                LogHelper::log("绑定渠道失败：uid: " . $uid . "  code: " . $channelCode);
                return apiSuccess([6, $uid]);
            }
            return apiSuccess([2, $uid]);
        }
        LogHelper::log("绑定的渠道不存在");
        return apiSuccess([3, $uid]);
    }

    /**
     * 用户提交基本信息
     * @param Request $request
     * @return array
     */
    public function submitInfo(Request $request) {
        $uid = $request->input('uid');
        if($decodeData = IdEncryptService::encryption($uid, 'decode')){
            $uid = $decodeData[0];
        }
        if (!$uid) {
            return apiErrcode('');
        }

        $name = $request->input('name');
        $phone = $request->input('phone');
        $wechatId = $request->input('wechat_id');
        if (TestingUserInfoService::saveInfo($uid, $name, $phone, $wechatId)) {
            return apiSuccess();
        }
        return apiError();
    }

    /**
     * 用户提交基本信息
     * @param Request $request
     * @param $uid
     * @return array
     */
    public function getUserInfo(Request $request, $uid) {
        if($decodeData = IdEncryptService::encryption($uid, 'decode')){
            $uid = $decodeData[0];
        }
        if (!$uid) {
            return apiErrcode('');
        }

        if ($userInfo = TestingUserInfoService::getOneByUid($uid)) {
            $data = [
                'uid' => $userInfo['uid'],
                'name' => $userInfo['name'],
                'phone' => $userInfo['phone'],
                'wechat_id' => $userInfo['wechat_id'],
            ];
            return apiSuccess($data);
        }
        return apiSuccess();
    }

    /**
     * 通过订单确认手机号
     * @param Request $request
     * @return array
     */
    public function checkPhoneByOrder(Request $request) {
        $phone = $request->input('phone');
        $uid = $request->input('uid');
        $tid = $request->input('tid');
        if($decodeData = IdEncryptService::encryption($uid, 'decode')){
            $uid = $decodeData[0];
        }
        if($decodeData = IdEncryptService::encryption($tid, 'decode')){
            $tid = $decodeData[0];
        }
        if (!$phone || !$uid || !$tid) {
            return apiFailed([
                'phone' => $phone,
                'uid' => $uid,
                'tid' => $uid
            ], '参数异常');
        }
        if (!preg_match('/^1([0-9]{9})/', $phone)) {
            return apiFailed(null, '手机号不正确，请联系你的营养师确认手机号');
        }
        $url = TestingConfig::getValue('jz.admin.base.url');
        $path = '/rpc/phone/order/info?param=' . OpensslEncryptHelper::encryptWithOpenssl(json_encode(['phone' => $phone]));
        $result = json_decode(curlRequest($url . $path, [], 'get'),true);
        if ($result['errcode'] == 200) {
            if ($data = $result['data']) {
                $status = $tid == BusinessHelper::getDimensionPayTid() ? 1 : 0;
                $result = TestingSyncOrderService::save($uid, $phone, $data['order_id'], $data['nutritionist_id'], $status);
                if (!$result) {
                    LogHelper::log("保存同步信息失败：uid: " . $uid . "  phone: " . $phone);
                }
                return apiSuccess($result);
            }
            return apiFailed(null, '系统异常');
        }
        return apiFailed($url . $path, '未查找到您的手机号（可能是您留了其他手机号），请和您的营养师核实后再来完成测评哦~');
    }

    /**
     * 根据手机号获取用户的ID信息
     * @param Request $request
     * @return array
     */
    public function getUserInfoByPhone(Request $request) {
        $phone = $request->input('phone');

        if (!$phone) {
            return apiFailed([
                'phone' => $phone,
            ], '参数异常');
        }

        if (!preg_match('/^1([0-9]{9})/', $phone)) {
            return apiFailed(null, '手机号不正确，请确认手机号');
        }
        $physiqueUrl = BusinessHelper::getPhysiqueQnUrl();
        //查询本地账户是否有信息，有直接返回
        $localUser = WechatUserService::getByPhone($phone);
        if ($localUser) {
            return apiSuccess([ 'url' => $physiqueUrl . $localUser['uid'] ]);
        }

        //查询帐号中心是否有信息，有同步信息到本地，并返回用户ID
        $url = BusinessHelper::getAccountUrl() . '/Api/ApiUser/getUserInfoByPhone?param=' . OpensslEncryptHelper::encryptWithOpenssl(json_encode(['phone' => $phone]));
        $result = json_decode(curlRequest($url, [], 'get'),true);
        if ($result['errcode'] == 200) {
            if ($remoteUser = $result['data']['user']) {
                $localUser = WechatUserService::getByUid($remoteUser['uid']);
                if ($localUser) {
                    WechatUserService::updateByUid($localUser['uid'], [
                        'phone' => $phone,
                    ]);
                } else {
                    WechatUserService::store([
                        'uid' => $remoteUser['uid'],
                        'nick_name' => $remoteUser['user_name'],
                        'sex' => $remoteUser['sex'],
                        'phone' => $remoteUser['mobile'],
                        'province' => $remoteUser['province'],
                        'city' => $remoteUser['city'],
                        'country' => $remoteUser['country'],
                        'headimgurl' => $remoteUser['wx_header'],
                        'from_url' => $remoteUser['referer_url'],
                        'from_appid' => $remoteUser['from_appid'],
                        'wx_union_id' => $remoteUser['wx_union_id'],
                    ]);
                }
                return apiSuccess([ 'url' => $physiqueUrl . $remoteUser['uid'] ]);
            }
        }

        return apiFailed(null, '用户信息不存在');
    }
}
